package server

import scala.actors._
import scala.collection.mutable._
import java.net._

/**
 * Keeps track of the pool of client nodes.
 * @author Jacob Biggs
 */
class ClientPool extends Actor {
	
  // All clients connected to server
	val activeClients = new ListBuffer[ ClientNode ]
	
	// All idle clients
	val idleClients = new ListBuffer[ ClientNode ]
	
	def act()
	{
		loop
		{
			react
			{
				case message : messages.StatusMessage =>
					handleStatusMessage(message)
			}
		}
	}
	
	/** 
	 * Takes a status message and update ClientNodes as necessary
	 * @author Jacob Biggs
	 * @param statusMessage	The message alerting the client pool of the client's status
	 */
	def handleStatusMessage(statusMessage : messages.StatusMessage)
	{
		statusMessage match
		{
			case messages.Active(clientAddress : InetAddress, clientName : String) =>
				activeClients += new ClientNode( clientName, clientAddress, sender )
				println("Client connected via " + clientAddress.getHostAddress() + " as '" + clientName + "'")
				
				sender ! messages.Notified
				sender ! messages.StatusRequest()
				
			case messages.Idle(clientAddress : InetAddress) =>
				val clientNode = activeClients.find( node => node.address == clientAddress ).get
				clientNode.status = client.Idle
				idleClients += clientNode
				println("Client '" + clientNode.name + "' at " + clientNode.address.getHostAddress() + " status set to Idle")
		}
		
	}
	
}